const connection = require('../app/database');

class SocialService {

  // 添加一个社交方式
  async create(userId, socialId, socialValue, socialLink) {
    try {
      const statement = `INSERT INTO user_social (user_id, social_id, social_value, social_link) VALUES (?, ?, ?, ?)`;
      const result = await connection.execute(statement, [userId, socialId, socialValue, socialLink]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个社交方式
  async remove(userId, s_id) {
    try {
      const statement = `DELETE FROM user_social WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [userId, s_id]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改一个社交方式
  async update(userId, socialId, socialValue, socialLink, s_id) {
    try {
      const statement = `UPDATE user_social SET social_id = ?, social_value = ?, social_link = ? WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [socialId, socialValue, socialLink, userId, s_id]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取社交列表
  async list(userId) {
    try {
      const statement = `
                      SELECT
                        us.id 'key',
                        us.social_id socialId,
                        st.social_key socialKey,
                        us.social_value socialValue,
                        us.social_link socialLink
                      FROM user_social us
                      LEFT JOIN social_type st ON us.social_id = st.id
                      WHERE user_id = ?`;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取社交类型
  async socialType(){
    try {
      const statement = `SELECT id, social_key socialKey FROM social_type`;
      const result = await connection.execute(statement);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new SocialService();
